package com.yubest.demo.anno.handler;

import com.yubest.demo.anno.Login;
import com.yubest.demo.anno.Repeat;
import com.yubest.demo.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.UUID;

/**
 * 重复提交处理器
 * @Author hweiyu
 * @Description
 * @Date 2021/3/23 10:58
 */
@Slf4j
public class RepeatHandler implements Handler {

    @Override
    public void execute(Context context) {
        Repeat repeat = context.getMethod().getAnnotation(Repeat.class);
        if (null == repeat) {
            return;
        }
        // SpEL表达式的上下文
        EvaluationContext spelContext = new StandardEvaluationContext();
        for (int i = 0; i < context.getArgNames().size(); i++) {
            // 方法的入参全部set进SpEL的上下文
            spelContext.setVariable(context.getArgNames().get(i), context.getArgValues().get(i));
        }
        Object key = new SpelExpressionParser().parseExpression(repeat.key()).getValue(spelContext);
        if (null != CacheUtil.get(key.toString(), String.class)) {
            throw new RuntimeException("请忽重复提交");
        }
        CacheUtil.set(key.toString(), UUID.randomUUID().toString(), repeat.expire());
    }

}
